//
//  PicturePhotoAlbumTool.m
//  BaibuSeller
//
//  Created by xmen on 2019/9/10.
//  Copyright © 2019 whawhawhat. All rights reserved.
//

#import "PicturePhotoAlbumTool.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import "MBProgressHUD+CRMHUD.h"
#import "Alert.h"


@interface PicturePhotoAlbumTool()<UIImagePickerControllerDelegate, TZImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (assign, nonatomic) NSInteger photoMaxCount; //上传图片的限制个数

@property (assign, nonatomic) NSInteger photoCount; // 已上传图片的个数

@property (weak, nonatomic) UIViewController *viewController;

@property (nonatomic, copy) ReturnImageArrayBlock returnImageArrayBlock; // 回调前拍照或者选中的图片(UIimage)数组



@end

@implementation PicturePhotoAlbumTool

+ (instancetype)sharedInstance {
    static PicturePhotoAlbumTool *picturePhotoAlbumTool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        picturePhotoAlbumTool = [[self alloc]init];
    });
    picturePhotoAlbumTool.editType = PhotoNotAllowsEditing;
    picturePhotoAlbumTool.saveType = PhotoNotSave;
    return picturePhotoAlbumTool;
}

- (void)showToolWithViewController:(UIViewController *)viewController photoMaxCount:(NSInteger)photoMaxCount photoCount:(NSInteger)photoCount returnImageArrayBlock:(ReturnImageArrayBlock)returnImageArrayBlock {
    self.viewController = viewController;
    self.photoCount = photoCount;
    self.photoMaxCount = photoMaxCount;
    self.returnImageArrayBlock = returnImageArrayBlock;
    [self addPhotoOperation];
}


/** 判断是否是相机的使用权限*/
- (BOOL)isCameraUseRights {
    BOOL isCameraUseRights = YES;
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        [Alert showAlertViewWithTitle:@"无法使用相机" message:@"请在iPhone的“设置-隐私-相机”中允许APP访问使用相机" dismissBlock:^(NSInteger index) {
            
        } cancelButtonIndex:0 titles:@[@"确定"]];
        isCameraUseRights = NO;
        
    }
    return isCameraUseRights;
}


#pragma mark -照片操作
- (void)addPhotoOperation {
    __weak typeof(self) weakSelf = self;
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"添加图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    //handler为手势方法添加处，这里就代替了之前UIAlertView中的代理协议方法,十分方便
    UIAlertAction * pAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([weakSelf isCameraUseRights]) {
            [weakSelf popCameraView];
        }
    }];
    UIAlertAction * PhotoAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
         [weakSelf PhotoAlbumOperation];
    }];
    [alert addAction:cancelAction];
    [alert addAction:pAction];
    [alert addAction:PhotoAction];
    [self.viewController presentViewController:alert animated:YES completion:nil];

}

/** 判断是否有相册访问权限*/
- (void)PhotoAlbumOperation {
    __block  BOOL isAlbumAccess = nil;
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status == PHAuthorizationStatusDenied) { // 用户拒绝当前App访问相册
            if (oldStatus != PHAuthorizationStatusNotDetermined) {// 没有访问相册的权限
                isAlbumAccess = NO;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [Alert showAlertViewWithTitle:@"无法访问相册" message:@"请在iPhone的“设置-隐私-照片”中允许APP访问你的照片" dismissBlock:^(NSInteger index) {
                        
                    } cancelButtonIndex:0 titles:@[@"确定"]];
                });
            }
            
        } else if (status == PHAuthorizationStatusAuthorized) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                isAlbumAccess = YES;
                [self popImageSelectView];
            });
            
        } else if (status == PHAuthorizationStatusRestricted) {
            isAlbumAccess = NO;
            [MBProgressHUD showError:@"因系统原因，无法访问相册"];
        }
    }];
}

- (void)popCameraView {
    if (self.photoCount >= self.photoMaxCount) {
        [MBProgressHUD showError:[NSString stringWithFormat:@"您最多只能上传%zd张图片", self.photoMaxCount]];
        return;
    }
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        NSArray *temp_MediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
        picker.mediaTypes = temp_MediaTypes;
        //修改为不可编辑
        //修改为可裁剪 只有拍照可以裁剪
        if (self.editType == PhotoNotAllowsEditing) {
            picker.allowsEditing = NO;
        } else if (self.editType == PhotoAllowsEditing) {
            picker.allowsEditing = YES;
        }
        [picker setDelegate:self];
    }
    
    [self.viewController presentViewController:picker animated:YES completion:nil];
}

- (void)popImageSelectView {
    
    if (self.photoCount >= self.photoMaxCount) {
        [MBProgressHUD showError:[NSString stringWithFormat:@"您最多只能上传%zd张图片", self.photoMaxCount]];
        return;
    }
    
    NSInteger imagesCount = self.photoMaxCount;
    if (self.photoCount != 0) {
        imagesCount = self.photoMaxCount - self.photoCount;
    }
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:imagesCount columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    //    imagePickerVc.selectedAssets = _selectedAssets; // 目前已经选中的图片数组
    imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.allowPickingGif = NO;
    //    imagePickerVc.allowPreview = NO;
    //    imagePickerVc.alwaysEnableDoneBtn = YES;
    [self.viewController.navigationController presentViewController:imagePickerVc animated:YES completion:nil];
}


#pragma mark TZImagePickerControllerDelegate
// 选择照片后的回调
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos{
    //获取图片的位置名称 ==
//    PHAsset * asset = assets[0];
//    CLLocation *location = asset.location;
//    double lon = location.coordinate.longitude;
//    double lat = location.coordinate.latitude;
//    PHImageManager * imageManager = [PHImageManager defaultManager];
//     [imageManager requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
//
//              NSURL *url = [info valueForKey:@"PHImageFileURLKey"];
//               NSString *str = [url absoluteString];   //url>string
//               NSArray *arr = [str componentsSeparatedByString:@"/"];
//               NSString *imgName = [arr lastObject];  // 图片名字
//               NSInteger length = imageData.length;   // 图片大小，单位B
//               UIImage * image = [UIImage imageWithData:imageData];
//
//              }];
    if (photos && photos.count > 0) {
        NSInteger currentSelect = self.photoCount + assets.count;
        if (currentSelect >= self.photoMaxCount + 1) {
            [MBProgressHUD showError:[NSString stringWithFormat:@"您最多只能上传%zd张图片", self.photoMaxCount]];
            return;
        }
        
        NSMutableArray *imageArray = [NSMutableArray array];
        [imageArray addObjectsFromArray:photos];
        
        if (self.returnImageArrayBlock) {
            self.returnImageArrayBlock(imageArray);
            self.returnImageArrayBlock = nil;
        }
        
    }
}

- (BOOL)startMediaBrowserFromViewController: (UIViewController*) controller usingDelegate: (id <UIImagePickerControllerDelegate, UINavigationControllerDelegate>) delegate {
    if (([UIImagePickerController isSourceTypeAvailable:
          UIImagePickerControllerSourceTypeSavedPhotosAlbum] == NO)
        || (delegate == nil)
        || (controller == nil))
        return NO;
    
    UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
    
    mediaUI.mediaTypes =
    [UIImagePickerController availableMediaTypesForSourceType:
     UIImagePickerControllerSourceTypeSavedPhotosAlbum];
    
    mediaUI.delegate = delegate;
    //修改为不可编辑
    //mediaUI.allowsEditing = YES;
    
    [controller presentViewController:mediaUI animated:YES completion:nil];
    return YES;
}


#pragma mark - UIImagePickerControllerDelegate(拍摄)
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:@"public.image"]){

        UIImage *img;
        if (self.editType == PhotoAllowsEditing) {
            //使用裁剪图
            img = [info objectForKey:UIImagePickerControllerEditedImage];
        } else {
            img = [info objectForKey:UIImagePickerControllerOriginalImage];
        }
        
        //用原图
        NSMutableArray *imageArray = [NSMutableArray array];
        [imageArray addObject:img];
        
        [picker dismissViewControllerAnimated:YES completion:nil];
        
        if (self.saveType == PhotoSave) {
             [self saveImageToAlbum:img];
        }
        
        if (self.returnImageArrayBlock) {
            self.returnImageArrayBlock(imageArray);
            self.returnImageArrayBlock = nil;
        } 
        
    } else if([mediaType isEqualToString:@"public.movie"]){
        [Alert showAlertViewWithTitle:@"抱歉" message:@"您拍摄的为视频，请拍摄图片。" dismissBlock:^(NSInteger index) {
            
        } cancelButtonIndex:0 titles:@[@"确定"]];
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}


/**
 保存到相册
 */
-(void)saveImageToAlbum:(UIImage *)image {
    __block  BOOL isAlbumAccess = nil;
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status == PHAuthorizationStatusDenied) { // 用户拒绝当前App访问相册
            if (oldStatus != PHAuthorizationStatusNotDetermined) {// 没有访问相册的权限
                isAlbumAccess = NO;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [Alert showAlertViewWithTitle:@"无权访问相册,相片无法写入" message:@"请在iPhone的“设置-隐私-照片”中允许访问你的照片" dismissBlock:^(NSInteger index) {
                        
                    } cancelButtonIndex:0 titles:@[@"确定"]];
                    
                });
            }
            
        } else if (status == PHAuthorizationStatusAuthorized) {
            dispatch_async(dispatch_get_main_queue(), ^{
                isAlbumAccess = YES;
                UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
            });
            
        } else if (status == PHAuthorizationStatusRestricted) {
            isAlbumAccess = NO;
            [MBProgressHUD showError:@"因系统原因，无法访问相册"];
        }
    }];
    
}


//必要实现的协议方法, 不然会崩溃
-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
}

@end
